package com.stn.zjx.givingtreasure.activity.userlogin;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.came.viewbguilib.ButtonBgUi;
import com.orhanobut.logger.Logger;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.event.UserResetPassEvent;
import com.vondear.rxtools.RxActivityTool;
import com.vondear.rxtools.RxNetTool;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class UserPassResetTwoActivity extends BaseActivity {


    //正在发送中
    boolean isSendLoading = false;
    int seconds = 60;
    EventHandler eh;
    Disposable sendvalidate__disposable = null;
    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.phone_tip)
    TextView phoneTip;
    @BindView(R.id.phone_tv)
    TextView phoneTv;
    @BindView(R.id.validate_bt)
    TextView validateBt;
    @BindView(R.id.validate_edit)
    EditText validateEdit;
    @BindView(R.id.phone_ll)
    LinearLayout phoneLl;
    @BindView(R.id.ok_bt)
    ButtonBgUi okBt;


    private String phone = "";

    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userpass_reset_two);
        ButterKnife.bind(this);
        initComponent();
        initData();
    }

    public void initComponent() {

        actionTitle.setText(getString(R.string.forgetpassword));
        validateBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!RxNetTool.isAvailable(UserPassResetTwoActivity.this)) {

                    showToast(getString(R.string.request_networkavailable));
                    return;
                }
                sendValidate();
                SMSSDK.getVerificationCode("86", "" + phone);

            }
        });
        eh = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {

                if (result == SMSSDK.RESULT_COMPLETE) {
                    //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Bundle bundle = new Bundle();
                                bundle.putString("phone", phone);
                                RxActivityTool.skipActivity(UserPassResetTwoActivity.this, UserPassResetThreeActivity.class, bundle);
                            }
                        });
                        //提交验证码成功
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        //获取验证码成功
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {


                                showToast(getString(R.string.sms_send_wait));
                            }
                        });

                    }
                } else {

                    runOnUiThread(() -> {
                        String str = ((Throwable) data).getMessage();
                        try {
                            JSONObject jb = new JSONObject(str);
                            showToast(jb.getString("detail"));

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    });
                    ((Throwable) data).printStackTrace();
                }
            }
        };
        SMSSDK.registerEventHandler(eh); //注册短信回调
    }

    private void initData() {
        phone = getIntent().getStringExtra("phone");
        phoneTip.setText(getString(R.string.yourself_phone) + phone);
        sendValidate();
        SMSSDK.getVerificationCode("86", "" + phone);

    }


    @Override
    public boolean isSupportSwipeBack() {
        return true;
    }

    @OnClick({R.id.back_bt, R.id.ok_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_bt:
                finish();
                break;
            case R.id.ok_bt:
                if (TextUtils.isEmpty(validateEdit.getText().toString().trim())) {

                    showToast(getString(R.string.sms_isnotempty));
                    return;
                }
                if (!RxNetTool.isAvailable(this)) {

                    showToast(getString(R.string.request_networkavailable));
                    return;
                }
                SMSSDK.submitVerificationCode("86", phone,
                        validateEdit.getText().toString().trim());
                break;
        }
    }


    //发送短信验证
    public void sendValidate() {
        sendvalidate__disposable = Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> observableEmitter) {
                while (isSendLoading && seconds > 0) {
                    seconds--;
                    observableEmitter.onNext(seconds);
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        sendvalidate__disposable.dispose();
                        e.printStackTrace();
                    }
                }
                observableEmitter.onComplete();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) {
                        isSendLoading = true;
                        validateBt.setBackgroundResource(R.drawable.round_darkgray_bg);
                        validateBt.setClickable(false);

                    }
                })
                .subscribe(new Consumer<Integer>() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void accept(Integer seconds) {
                        isSendLoading = true;
                        validateBt.setText(getString(R.string.surplus)
                                + "" + seconds + getString(R.string.seconds)
                                + getString(R.string.resend));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        sendvalidate__disposable.dispose();
                        reset_sendValidate();
                    }
                }, new Action() {
                    @Override
                    public void run() {
                        reset_sendValidate();
                    }
                });


    }

    //重置发送短信按钮
    public void reset_sendValidate() {
        isSendLoading = false;
        validateBt.setText(getString(R.string.get_validate));
        validateBt.setBackgroundResource(R.drawable.round_default_theme_bg);
        seconds = 60;
        validateBt.setClickable(true);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (sendvalidate__disposable != null) {
            sendvalidate__disposable.dispose();
            reset_sendValidate();
        }
        SMSSDK.unregisterEventHandler(eh);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void UserResetPassEvent(UserResetPassEvent event) {
        finish();
    }

}
